<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>文件拿取</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.7.2/css/all.min.css" rel="stylesheet">
</head>
<body class="bg-gray-50 font-sans">
    <div class="container mx-auto px-4 py-8 max-w-5xl">
        <!-- 导航栏 -->
        <nav class="flex items-center justify-between mb-8">
            <div class="flex items-center space-x-2">
                <i class="fa fa-folder-open text-blue-500 text-2xl"></i>
                <h1 class="text-xl font-bold text-gray-800">文件拿取</h1>
            </div>
            <a href="/upload" class="flex items-center px-4 py-2 bg-blue-500 text-white rounded-md">
                <i class="fa fa-upload mr-2"></i> 文件投送
            </a>
        </nav>
        
        <!-- 搜索区域 -->
        <div class="bg-white rounded-lg p-6 mb-8">
            <h2 class="text-lg font-semibold text-gray-800 mb-4">文件搜索</h2>
            <div class="flex flex-col sm:flex-row gap-4">
                <input type="text" id="fileSearch" placeholder="输入转出文件夹包含的字符" 
                       class="flex-1 px-4 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500">
                <button id="submitBtn" 
                        class="px-6 py-2 bg-blue-500 text-white rounded-md">
                    <i class="fa fa-search mr-2"></i> 搜索
                </button>
            </div>
            <div id="errorMessage" class="mt-2 text-red-500 text-sm hidden"></div>
        </div>
        
        <!-- 搜索结果 -->
        <div class="bg-white rounded-lg p-6">
            <div class="flex items-center justify-between mb-4">
                <h2 class="text-lg font-semibold text-gray-800">搜索结果</h2>
                <div id="resultCount" class="text-sm text-gray-500">0 个文件</div>
            </div>
            
            <div class="overflow-x-auto">
                <table class="min-w-full divide-y divide-gray-200">
                    <thead class="bg-gray-50">
                        <tr>
                            <th scope="col" class="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase tracking-wider">操作</th>
                            <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">名称</th>
                        </tr>
                    </thead>
                    <tbody id="fileTableBody" class="bg-white divide-y divide-gray-200">
                        <!-- 动态内容将在这里渲染 -->
                        <tr class="text-center">
                            <td colspan="2" class="px-6 py-12 text-gray-500">
                                <div class="max-w-md flex flex-col items-center">
                                    <i class="fa fa-search text-4xl mb-4 text-gray-300"></i>
                                    <p>请输入关键词进行搜索</p>
                                </div>
                            </td>
                        </tr>
                    </tbody>
                </table>
            </div>
            
            <!-- 无结果状态 -->
            <div id="noResult" class="hidden text-center py-12">
                <i class="fa fa-folder-open text-4xl mb-4 text-gray-300"></i>
                <p class="text-gray-500">没有找到匹配的文件</p>
            </div>
            
            <!-- 加载状态 -->
            <div id="loading" class="hidden text-center py-12">
                <div class="inline-block rounded-full h-8 w-8 border-b-2 border-blue-500"></div>
                <p class="mt-2 text-gray-500">搜索中...</p>
            </div>
        </div>
    </div>

    <script>
        // 搜索API
        async function searchAPI(query) {
            try {
                const response = await fetch(`/api/search?query=${encodeURIComponent(query)}`);
                if (!response.ok) {
                    throw new Error(`HTTP错误! 状态: ${response.status}`);
                }
                return await response.json();
            } catch (error) {
                console.error('搜索API错误:', error);
                showError(`搜索失败: ${error.message}`);
                throw error;
            }
        }

        // 下载文件
        function downloadFile(path, filename) {
            // const encodedPath = encodeURIComponent(path);
            // console.log(path);
            // filePath = String(path).substring(5);
            filePath = String(path);
            console.log(filePath);
            const link = document.createElement('a');
            link.href = `/api/download?path=${filePath}`;
            link.download = filename;
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
        }

        // 渲染文件表格
        function renderFileTable(data) {
            const tableBody = document.getElementById('fileTableBody');
            const noResult = document.getElementById('noResult');
            const resultCount = document.getElementById('resultCount');
            
            // 清空表格
            tableBody.innerHTML = '';
            
            if (data.length === 0) {
                noResult.classList.remove('hidden');
                resultCount.textContent = '0 个文件';
                return;
            }
            
            noResult.classList.add('hidden');
            resultCount.textContent = `${data.length} 个文件/文件夹`;
            
            // 渲染文件和文件夹
            data.forEach(item => {
                renderFileItem(item, tableBody);
            });
        }

        // 渲染单个文件或文件夹
        function renderFileItem(item, parentElement, level = 0) {
            const row = document.createElement('tr');
            row.dataset.path = item.path;
            row.dataset.type = item.type;
            row.className = 'file-row';
            
            // 名称列
            const nameCell = document.createElement('td');
            nameCell.className = 'px-6 py-4 whitespace-nowrap';
            
            // 使用网格系统确保对齐
            const nameContent = document.createElement('div');
            nameContent.className = 'flex items-center';
            
            // 缩进
            const indentSpan = document.createElement('span');
            indentSpan.className = `w-[${level * 24}px]`;
            
            if (item.type === 'directory') {
                const folderIcon = document.createElement('i');
                folderIcon.className = 'fa fa-folder text-yellow-500 mr-2';
                
                const folderName = document.createElement('span');
                folderName.className = 'font-medium text-gray-900';
                folderName.textContent = item.name;
                
                const folderWrapper = document.createElement('div');
                folderWrapper.className = 'flex items-center cursor-pointer';
                folderWrapper.appendChild(folderIcon);
                folderWrapper.appendChild(folderName);
                
                // folderWrapper.addEventListener('click', () => toggleFolder(item.path));
                
                nameContent.appendChild(indentSpan);
                nameContent.appendChild(folderWrapper);
                nameCell.appendChild(nameContent);
            } else {
                const fileIcon = document.createElement('i');
                fileIcon.className = 'fa fa-file text-gray-400 mr-2';
                
                const fileName = document.createElement('span');
                fileName.className = 'text-gray-700';
                fileName.textContent = item.name;
                
                const fileWrapper = document.createElement('div');
                fileWrapper.className = 'flex items-center';
                fileWrapper.appendChild(fileIcon);
                fileWrapper.appendChild(fileName);
                
                nameContent.appendChild(indentSpan);
                nameContent.appendChild(fileWrapper);
                nameCell.appendChild(nameContent);
            }
            
            // 操作列
            const actionCell = document.createElement('td');
            actionCell.className = 'px-6 py-4 whitespace-nowrap text-right text-sm font-medium';
            
            if (item.type === 'file') {
                const downloadBtn = document.createElement('a');
                // downloadBtn.href = '#';
                downloadBtn.className = 'text-blue-500';
                downloadBtn.innerHTML = '<i class="fa fa-download mr-1"></i> 下载';
                downloadBtn.addEventListener('click', (e) => {
                    e.preventDefault();
                    downloadFile(item.path, item.name);
                });
                actionCell.appendChild(downloadBtn);
            } else {
                actionCell.innerHTML = '<span class="text-gray-400">--</span>';
            }
            
            // 添加行到表格
            row.appendChild(actionCell);
            row.appendChild(nameCell);
            
            parentElement.appendChild(row);
            
            // 为文件夹添加子行标记
            if (item.type === 'directory' && item.children && item.children.length > 0) {
                row.dataset.hasChildren = 'true';
                
                // 递归渲染子项
                item.children.forEach(child => {
                    renderFileItem(child, parentElement, level + 1);
                });
            }
        }

        // 显示错误信息
        function showError(message) {
            const errorElement = document.getElementById('errorMessage');
            errorElement.textContent = message;
            errorElement.classList.remove('hidden');
            
            setTimeout(() => {
                errorElement.classList.add('hidden');
            }, 5000);
        }

        // 初始化页面
        document.addEventListener('DOMContentLoaded', () => {
            document.getElementById('submitBtn').addEventListener('click', async function() {
                const searchText = document.getElementById('fileSearch').value.trim();
                const loading = document.getElementById('loading');
                const fileTableBody = document.getElementById('fileTableBody');
                
                // 清空表格和错误信息
                fileTableBody.innerHTML = '';
                document.getElementById('errorMessage').classList.add('hidden');
                document.getElementById('noResult').classList.add('hidden');
                
                // 显示加载状态
                loading.classList.remove('hidden');
                
                try {
                    // 调用API
                    const result = await searchAPI(searchText);
                    
                    // 移除加载状态
                    loading.classList.add('hidden');
                    
                    // 渲染结果
                    renderFileTable(result.results);
                } catch (error) {
                    // 错误处理在searchAPI中完成
                    loading.classList.add('hidden');
                }
            });
            
        });
    </script>
</body>
</html>    